package com.luoye.lj.config;
import com.luoye.lj.platform.model.domain.AuthInfo;
import com.luoye.lj.platform.service.CustomUserDetailsService;
import com.luoye.lj.platform.service.impl.AuthServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.util.StringUtils;

import java.util.List;

@Configuration
@EnableWebSecurity
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Autowired
    private AuthServiceImpl authService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        List<AuthInfo> authInfoList=authService.getAll();
        if(authInfoList!=null) {
            for (AuthInfo authInfo : authInfoList) {
                String patterns=authInfo.getPatterns();
                if(!StringUtils.isEmpty(patterns)){
                    String []patternList=patterns.split(",");
                    for(String pattern:patternList) {
                        log.info(pattern+"-"+authInfo.getAuthname());
                        http.authorizeRequests().antMatchers(pattern).hasAnyAuthority(authInfo.getAuthname());
                    }
                }
            }
        }
        http
                .csrf()
                    .ignoringAntMatchers("/login","/logout")
                    .and()
                .authorizeRequests()
//                    .mvcMatchers("/system/auth/**").servletPath("/auth/login").hasAnyAuthority("A_Develop_Auth1")
                    .antMatchers("/component/**","/css/**","/js/**","/error/**").permitAll()
//                    .antMatchers("/system/manager/**").hasAnyAuthority("A_System_Manager")
//                    .antMatchers("/system/role/**").hasAnyAuthority("A_Develop_Role")
//                    .antMatchers("/system/auth/**").hasAnyAuthority("A_Develop_Auth")
//                    .antMatchers("/system/logger/**").hasAnyAuthority("A_System_LogList")
                    .anyRequest().authenticated()
                    // 自定义FilterInvocationSecurityMetadataSource
//                    .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
//                        @Override
//                        public <O extends FilterSecurityInterceptor> O postProcess(
//                                O fsi) {
//                            fsi.setSecurityMetadataSource(mySecurityMetadataSource(fsi.getSecurityMetadataSource()));
//                            return fsi;
//                        }
//                    })
                    .and()
                .formLogin()
                    .loginPage("/auth/login")
                    .loginProcessingUrl("/login")//配置登录请求路径
                    .defaultSuccessUrl("/auth/default")
                    .permitAll()
                    .and()
                .logout()
//                    .logoutUrl("/my/logout")
                    .logoutSuccessUrl("/auth/login")
//                    .logoutSuccessHandler(logoutSuccessHandler)
                    .invalidateHttpSession(true)
//                    .addLogoutHandler(logoutHandler)
//                    .deleteCookies(cookieNamesToClear)
                    .permitAll()
                    .and()
                .headers().frameOptions().sameOrigin();
    }

    @Override
    public UserDetailsService userDetailsService() {
//        UserDetails user =
//                User.withDefaultPasswordEncoder()
//                        .username("user")
//                        .password("password")
//                        .roles("USER")
//                        .build();
//
//        return new InMemoryUserDetailsManager(user);
        return userDetailsService;
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


//    @Bean
//    public AppFilterInvocationSecurityMetadataSource mySecurityMetadataSource(FilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource) {
//        AppFilterInvocationSecurityMetadataSource securityMetadataSource = new AppFilterInvocationSecurityMetadataSource(filterInvocationSecurityMetadataSource);
//        return securityMetadataSource;
//    }
}